import promptPlusService from '@/services/prompt-plus';
import {
  BulbOutlined,
  ClockCircleOutlined,
  CloudUploadOutlined,
  CopyOutlined,
  DeleteOutlined,
  EditOutlined,
  FileTextOutlined,
  FilterOutlined,
  FolderOutlined,
  ImportOutlined,
  MailOutlined,
  PlusOutlined,
  QrcodeOutlined,
  SearchOutlined,
  StarOutlined,
  ThunderboltOutlined,
  UnorderedListOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  Avatar,
  Button,
  Card,
  Collapse,
  Divider,
  Dropdown,
  Form,
  Input,
  Layout,
  Menu,
  message,
  Modal,
  Pagination,
  Radio,
  Select,
  Space,
  Tabs,
  Tag,
  Tooltip,
  Upload,
} from 'antd';
import OpenAI from 'openai';
import { useEffect, useRef, useState } from 'react';

const { Sider, Content } = Layout;
const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;
const { Panel } = Collapse;

const DEFAULT_PAGE_SIZE = 9;

const PromptManagement = () => {
  // State management
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isFolderModalVisible, setIsFolderModalVisible] = useState(false);
  const [isImportModalVisible, setIsImportModalVisible] = useState(false);
  const [isPromptDetailVisible, setIsPromptDetailVisible] = useState(false);
  const [isAssistantVisible, setIsAssistantVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isShareModalVisible, setIsShareModalVisible] = useState(false);
  const [isOptimizeModalVisible, setIsOptimizeModalVisible] = useState(false);
  const [importType, setImportType] = useState('text');
  const [activeFolder, setActiveFolder] = useState('全部提示词');
  const [searchText, setSearchText] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedPrompt, setSelectedPrompt] = useState(null);
  const [editingPrompt, setEditingPrompt] = useState(null);
  const [optimizingPrompt, setOptimizingPrompt] = useState(null);
  const [optimizedContent, setOptimizedContent] = useState('');
  const [selectedModel, setSelectedModel] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState('');
  const [fileList, setFileList] = useState([]);
  const [models, setModels] = useState([]);
  const [promptTemplates, setPromptTemplates] = useState([]);
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [folderForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [shareForm] = Form.useForm();
  const [assistantForm] = Form.useForm();
  const [optimizeForm] = Form.useForm();
  const optimizedTextAreaRef = useRef(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedContent, setGeneratedContent] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    total: 0,
  });

  const [activeTab, setActiveTab] = useState('base');
  const [templateType, setTemplateType] = useState('base');

  // Data state
  const [prompts, setPrompts] = useState([]);
  const [folders, setFolders] = useState([
    { id: 'all', name: '全部提示词', icon: <FolderOutlined /> },
    { id: 'favorites', name: '收藏夹', icon: <StarOutlined /> },
  ]);

  const tags = ['工作', '学习', '创意', '重要'];
  const categories = ['写作', '编程', '设计', '营销', '工作', '学习'];

  // Filter prompts
  const filteredPrompts = prompts.filter((prompt) => {
    const matchesFolder =
      activeFolder === '全部提示词' ||
      (prompt.folder && prompt.folder === folders.find((f) => f.name === activeFolder)?.id);
    const matchesSearch =
      searchText === '' ||
      (prompt.title && prompt.title.toLowerCase().includes(searchText.toLowerCase())) ||
      (prompt.description && prompt.description.toLowerCase().includes(searchText.toLowerCase()));
    return matchesFolder && matchesSearch;
  });

  // Current page prompts
  const currentPrompts = filteredPrompts.slice(
    (currentPage - 1) * DEFAULT_PAGE_SIZE,
    currentPage * DEFAULT_PAGE_SIZE,
  );

  // Initialize data
  useEffect(() => {
    fetchPrompts();
    fetchFolders();
    fetchModels();
    fetchTemplates();
  }, [pagination.current, pagination.pageSize, searchText]);

  // API functions
  const fetchPrompts = async (folderId = 'all', search = '', page = 1) => {
    try {
      setLoading(true);
      const response = await promptPlusService.myPrompt.getMyPrompts({
        page: pagination.current,
        size: pagination.pageSize,
        keyword: searchText,
      });
      setPrompts(response.data || response); // Handle both response formats
      setPagination((prev) => ({
        ...prev,
        total: response.total || response.length || 0,
      }));
    } catch (error) {
      message.error('获取提示词失败');
      console.error('Error fetching prompts:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchFolders = async () => {
    try {
      const response = await promptPlusService.myFolder.getAllMyFolders();
      setFolders((prev) => [
        ...prev.filter((f) => f.id === 'all' || f.id === 'favorites'),
        ...(response.data || response || []),
      ]);
    } catch (error) {
      message.error('获取文件夹失败');
      console.error('Error fetching folders:', error);
    }
  };

  const fetchModels = async () => {
    try {
      const response = await promptPlusService.model.getAllModels();
      setModels(response.data || response || []);
    } catch (error) {
      message.error('获取模型失败');
      console.error('Error fetching models:', error);
    }
  };

  const fetchTemplates = async () => {
    try {
      const response = await promptPlusService.template.getAllTemplates();
      setPromptTemplates(response.data || response || []);
    } catch (error) {
      message.error('获取模板失败');
      console.error('Error fetching templates:', error);
    }
  };

  // Event handlers
  const handleFolderClick = (folderName) => {
    setActiveFolder(folderName);
    setCurrentPage(1);
  };

  const showModal = () => {
    form.resetFields();
    setIsModalVisible(true);
  };

  const showImportModal = () => {
    setIsImportModalVisible(true);
    setImportType('text');
    setFileList([]);
  };

  const showPromptDetail = (prompt) => {
    setSelectedPrompt(prompt);
    setIsPromptDetailVisible(true);
  };

  const showAssistant = () => {
    setIsAssistantVisible(true);
  };

  const showEditModal = (prompt) => {
    setEditingPrompt(prompt);
    const folderId = Number(prompt.folder);
    const currentFolder = Number.isFinite(folderId) && folders.find((f) => f.id === folderId);
    editForm.setFieldsValue({
      title: prompt.title,
      description: prompt.description,
      content: prompt.content,
      category: prompt.category,
      folder: currentFolder ? currentFolder.id : 'all',
      tags: prompt.tags || [],
      version: prompt.version || 'latest',
      roleName: prompt.roleName,
      base: prompt.base,
      reusePrefix: prompt.reusePrefix,
      selenium: prompt.selenium,
      playwright: prompt.playwright,
      both: prompt.both,
    });
    setIsEditModalVisible(true);
  };

  const showOptimizeModal = (prompt) => {
    setOptimizingPrompt(prompt);
    optimizeForm.setFieldsValue({
      originalContent: prompt.content,
      optimizedContent: '',
    });
    setIsOptimizeModalVisible(true);
    setOptimizedContent('');
    setSelectedModel('');
    setSelectedTemplate('');
  };

  // Modal cancel handlers
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const handleImportCancel = () => {
    setIsImportModalVisible(false);
    setFileList([]);
  };

  const handlePromptDetailCancel = () => {
    setIsPromptDetailVisible(false);
  };

  const handleEditCancel = () => {
    setIsEditModalVisible(false);
    editForm.resetFields();
  };

  const handleShareCancel = () => {
    setIsShareModalVisible(false);
    shareForm.resetFields();
  };

  const handleOptimizeCancel = () => {
    setIsOptimizeModalVisible(false);
    optimizeForm.resetFields();
    setOptimizedContent('');
    setSelectedModel('');
    setSelectedTemplate('');
    setIsOptimizing(false);
  };

  // File upload handler
  const handleFileUpload = (info) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    setFileList(fileList);

    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
      const file = info.file.originFileObj;
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target.result;
        optimizeForm.setFieldsValue({
          fileContent: content,
        });
      };
      reader.readAsText(file);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }
  };

  // Form submission handlers
  const handleSubmit = async (values) => {
    try {
      const newPrompt = {
        title: values.title,
        description: values.description,
        content: values.content,
        category: values.category || '写作',
        folder: folders.find((f) => f.name === values.folder)?.id || 'all',
        tags: values.tags || [],
        version: values.version || 'latest',
        roleName: values.roleName,
        base: values.base,
        reusePrefix: values.reusePrefix,
        selenium: values.selenium,
        playwright: values.playwright,
        both: values.both,
      };

      await promptPlusService.myPrompt.addMyPrompt(newPrompt);
      message.success('提示词创建成功');
      setIsModalVisible(false);
      form.resetFields();
      fetchPrompts();
    } catch (error) {
      message.error('创建提示词失败');
      console.error('Error creating prompt:', error);
    }
  };

  const handleFolderSubmit = async (values) => {
    try {
      const newFolder = {
        name: values.name,
      };

      await promptPlusService.myFolder.addMyFolder(newFolder);
      message.success('文件夹创建成功');
      setIsFolderModalVisible(false);
      folderForm.resetFields();
      fetchFolders();
    } catch (error) {
      message.error('创建文件夹失败');
      console.error('Error creating folder:', error);
    }
  };

  const handleImport = async (values) => {
    try {
      let content = '';
      if (importType === 'text') {
        content = values.content || '';
      } else if (importType === 'file') {
        content = values.fileContent || '';
      } else if (importType === 'code') {
        // Handle code import logic here
        content = values.code || '';
      }

      const newPrompt = {
        title: `导入的提示词-${new Date().getTime()}`,
        description: content.length > 100 ? `${content.substring(0, 100)}...` : content,
        content: content,
        category: values.category || '写作',
        folder: folders.find((f) => f.name === values.folder)?.id || 'all',
        tags: [],
        version: values.version || 'latest',
        roleName: values.roleName,
        base: values.base,
        reusePrefix: values.reusePrefix,
        selenium: values.selenium,
        playwright: values.playwright,
        both: values.both,
      };

      await promptPlusService.myPrompt.addMyPrompt(newPrompt);
      message.success('提示词导入成功');
      setIsImportModalVisible(false);
      setFileList([]);
      fetchPrompts();
    } catch (error) {
      message.error('导入提示词失败');
      console.error('Error importing prompt:', error);
    }
  };

  const handleDeletePrompt = async (id) => {
    try {
      await promptPlusService.myPrompt.deleteMyPrompt(id);
      message.success('提示词删除成功');
      fetchPrompts();
    } catch (error) {
      message.error('删除提示词失败');
      console.error('Error deleting prompt:', error);
    }
  };

  const handleCopyPrompt = async (prompt) => {
    try {
      const newPrompt = {
        ...prompt,
        title: `${prompt.title} (副本)`,
        id: undefined, // Remove the id to create a new copy
      };

      await promptPlusService.myPrompt.addMyPrompt(newPrompt);
      message.success('提示词复制成功');
      fetchPrompts();
    } catch (error) {
      message.error('复制提示词失败');
      console.error('Error copying prompt:', error);
    }
  };

  const handleCopyPromptContent = (prompt) => {
    if (!prompt) return;

    try {
      navigator.clipboard
        .writeText(prompt.content || '')
        .then(() => {
          message.success('提示词内容已复制到剪贴板');
        })
        .catch((err) => {
          console.error('复制失败:', err);
          message.error('复制失败，请手动复制');
        });
    } catch (error) {
      console.error('处理提示词复制时出错:', error);
      message.error('复制过程中出错');
    }
  };

  const handleDeleteFolder = async (folderName) => {
    if (folderName === '全部提示词') {
      message.warning('不能删除"全部提示词"文件夹');
      return;
    }

    try {
      const folder = folders.find((f) => f.name === folderName);
      if (!folder) return;

      await promptPlusService.myFolder.deleteMyFolder(folder.id);
      message.success('文件夹删除成功');
      fetchFolders();
    } catch (error) {
      message.error('删除文件夹失败');
      console.error('Error deleting folder:', error);
    }
  };

  const handleEditSubmit = async (values) => {
    if (!editingPrompt) return;
    try {
      const updatedPrompt = {
        ...editingPrompt,
        title: values.title,
        description: values.description,
        content: values.content,
        category: values.category,
        folder: values.folder,
        tags: values.tags || [],
        version: values.version || 'latest',
        roleName: values.roleName,
        base: values.base,
        reusePrefix: values.reusePrefix,
        selenium: values.selenium,
        playwright: values.playwright,
        both: values.both,
      };

      await promptPlusService.myPrompt.updateMyPrompt(editingPrompt.id, updatedPrompt);
      message.success('提示词更新成功');
      setIsEditModalVisible(false);
      fetchPrompts();
    } catch (error) {
      message.error('更新提示词失败');
      console.error('Error updating prompt:', error);
    }
  };

  const handleShareSubmit = async (values) => {
    if (!selectedPrompt) return;

    try {
      await promptPlusService.myPrompt.sharePrompt({
        promptId: selectedPrompt.id,
        email: values.email,
        message: values.message,
      });
      message.success(`提示词已分享至: ${values.email}`);
      setIsShareModalVisible(false);
    } catch (error) {
      message.error('分享提示词失败');
      console.error('Error sharing prompt:', error);
    }
  };

  const handleAssistantSubmit = async (values) => {
    try {
      const selectedModelObj = models.find((m) => m.identifier === values.model);
      if (!selectedModelObj) {
        message.error('请先选择优化模型');
        return;
      }

      setIsGenerating(true);
      setGeneratedContent('');
      message.loading('正在生成提示词...', 0);

      const openai = new OpenAI({
        apiKey: selectedModelObj.apiKey,
        baseURL: selectedModelObj.apiUrl,
        dangerouslyAllowBrowser: true,
      });

      const stream = await openai.chat.completions.create({
        model: selectedModelObj.defaultSearch || selectedModelObj.identifier,
        messages: [
          {
            role: 'system',
            content: '你是一个专业的提示词生成助手',
          },
          {
            role: 'user',
            content: `请创建一个用于${values.type}的提示词，具体要求如下:\n\n${values.requirements}\n\n请提供专业、详细的提示词。`,
          },
        ],
        temperature: 0.7,
        max_tokens: 2000,
        stream: true,
      });

      let fullContent = '';
      for await (const chunk of stream) {
        const content = chunk.choices[0]?.delta?.content || '';
        fullContent += content;
        setGeneratedContent(fullContent);
      }

      message.destroy();
      message.success('提示词生成完成');
    } catch (error) {
      console.error('生成失败:', error);
      message.destroy();
      message.error(`生成失败: ${error.message}`);
      setIsGenerating(false);
    } finally {
      setIsGenerating(false);
    }
  };

  // Auto-scroll for optimized content
  useEffect(() => {
    if (optimizedTextAreaRef.current) {
      optimizedTextAreaRef.current.resizableTextArea.textArea.scrollTop =
        optimizedTextAreaRef.current.resizableTextArea.textArea.scrollHeight;
    }
  }, [optimizedContent]);

  // Optimize prompt - stream processing
  const handleOptimizeSubmit = async () => {
    const values = optimizeForm.getFieldsValue();
    const selectedTemplateObj = promptTemplates.find((t) => t.name === selectedTemplate);
    const selectedModelObj = models.find((m) => m.identifier === selectedModel);

    if (!selectedModel || !selectedTemplateObj) {
      message.error('请选择模型和模板');
      return;
    }

    if (!selectedModelObj?.apiKey) {
      message.error('请先配置所选模型的API Key');
      return;
    }

    setIsOptimizing(true);
    message.loading('正在优化提示词...', 0);
    setOptimizedContent('');

    try {
      const openai = new OpenAI({
        apiKey: selectedModelObj.apiKey,
        baseURL: selectedModelObj.apiUrl,
        dangerouslyAllowBrowser: true,
      });

      const templateContent = selectedTemplateObj.content.replace(
        '{originalPrompt}',
        values.originalContent,
      );

      const stream = await openai.chat.completions.create({
        model: selectedModelObj.defaultSearch || selectedModelObj.identifier,
        messages: [
          {
            role: 'system',
            content: '你是一个专业的提示词优化助手',
          },
          {
            role: 'user',
            content: templateContent,
          },
        ],
        temperature: 0.7,
        max_tokens: 2000,
        stream: true,
      });

      let fullResponse = '';
      for await (const chunk of stream) {
        const content = chunk.choices[0]?.delta?.content || '';
        fullResponse += content;
        setOptimizedContent((prev) => prev + content);
      }

      optimizeForm.setFieldsValue({
        optimizedContent: fullResponse,
      });

      message.destroy();
      message.success('提示词优化完成');
    } catch (error) {
      console.error('优化失败:', error);
      message.destroy();
      message.error(`优化失败: ${error.message}`);
    } finally {
      setIsOptimizing(false);
    }
  };

  const handleSaveOptimizedPrompt = async () => {
    if (!optimizingPrompt) return;

    try {
      const values = optimizeForm.getFieldsValue();
      const newPrompt = {
        ...optimizingPrompt,
        title: `${optimizingPrompt.title} (优化版)`,
        description: `优化后的提示词: ${optimizingPrompt.description}`,
        content: values.optimizedContent || optimizedContent,
        version: optimizingPrompt.version || 'latest',
        roleName: optimizingPrompt.roleName,
      };

      await promptPlusService.myPrompt.updateMyPrompt(newPrompt);
      message.success('优化后的提示词保存成功');
      setIsOptimizeModalVisible(false);
      fetchPrompts();
    } catch (error) {
      message.error('保存优化提示词失败');
      console.error('Error saving optimized prompt:', error);
    }
  };

  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider
        width={250}
        style={{
          background: '#f9fafb',
          borderRight: '1px solid #e5e7eb',
          padding: '16px',
        }}
      >
        <div style={{ marginBottom: '24px' }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            style={{ width: '100%', marginBottom: '8px', background: '#8b5cf6' }}
            onClick={showModal}
          >
            新建提示词
          </Button>
          <Button
            icon={<ImportOutlined />}
            style={{ width: '100%', marginBottom: '8px' }}
            onClick={showImportModal}
          >
            导入提示词
          </Button>
          <Button icon={<BulbOutlined />} style={{ width: '100%' }} onClick={showAssistant}>
            Prompt助手
          </Button>
        </div>

        <div style={{ marginBottom: '24px' }}>
          <h3 style={{ color: '#374151', marginBottom: '12px' }}>文件夹</h3>
          <ul style={{ listStyle: 'none', padding: 0 }}>
            {folders.map((folder, index) => (
              <li key={folder.id} style={{ marginBottom: '4px' }}>
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '8px 12px',
                    borderRadius: '6px',
                    backgroundColor: activeFolder === folder.name ? '#ede9fe' : 'transparent',
                    color: activeFolder === folder.name ? '#7c3aed' : '#374151',
                    cursor: 'pointer',
                  }}
                  onClick={() => handleFolderClick(folder.name)}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    {folder.icon}
                    <span>{folder.name}</span>
                  </div>
                  {index !== 0 && (
                    <Dropdown
                      overlay={
                        <Menu>
                          <Menu.Item key="delete" onClick={() => handleDeleteFolder(folder.name)}>
                            删除
                          </Menu.Item>
                        </Menu>
                      }
                      trigger={['click']}
                    >
                      <DeleteOutlined style={{ color: '#ef4444', fontSize: '12px' }} />
                    </Dropdown>
                  )}
                </div>
              </li>
            ))}
          </ul>
        </div>

        <div style={{ marginBottom: '24px' }}>
          <h3 style={{ color: '#374151', marginBottom: '12px' }}>标签</h3>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
            {tags.map((tag, index) => (
              <Tag
                key={tag}
                color={index === 0 ? 'blue' : index === 1 ? 'green' : index === 2 ? 'gold' : 'red'}
              >
                {tag}
              </Tag>
            ))}
          </div>
        </div>

        <div style={{ marginTop: 'auto', paddingTop: '24px' }}>
          <Button
            icon={<PlusOutlined />}
            style={{ width: '100%', marginBottom: '8px' }}
            onClick={() => setIsFolderModalVisible(true)}
          >
            新建文件夹
          </Button>
        </div>
      </Sider>

      <Layout>
        <Content style={{ padding: '24px', background: '#fff' }}>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '24px',
            }}
          >
            <h1 style={{ fontSize: '24px', fontWeight: 'bold', margin: 0 }}>{activeFolder}</h1>
            <Space>
              <Input
                placeholder="搜索提示词..."
                prefix={<SearchOutlined />}
                style={{ width: 300 }}
                value={searchText}
                onChange={(e) => {
                  setSearchText(e.target.value);
                  setCurrentPage(1);
                }}
              />
              <Button icon={<FilterOutlined />} />
              <Button icon={<UnorderedListOutlined />} />
            </Space>
          </div>

          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(3, 1fr)',
              gap: '16px',
              marginBottom: '24px',
            }}
          >
            {currentPrompts.length > 0 ? (
              currentPrompts.map((prompt) => (
                <Card
                  key={prompt.id}
                  hoverable
                  style={{ borderRadius: '12px', borderColor: '#e5e7eb' }}
                  bodyStyle={{ padding: '16px' }}
                  onClick={() => showPromptDetail(prompt)}
                >
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'flex-start',
                      marginBottom: '12px',
                    }}
                  >
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '12px',
                        flex: 1,
                        minWidth: 0,
                      }}
                    >
                      <Avatar style={{ backgroundColor: '#8b5cf6', color: '#fff', flexShrink: 0 }}>
                        {prompt.title?.charAt(0) || 'P'}
                      </Avatar>
                      <div style={{ minWidth: 0 }}>
                        <div
                          style={{
                            fontWeight: 500,
                            fontSize: '16px',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                          }}
                        >
                          {prompt.title}
                        </div>
                        <div
                          style={{
                            color: '#8b5cf6',
                            fontSize: '14px',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                          }}
                        >
                          {prompt.category}
                        </div>
                      </div>
                    </div>
                    <Tag color="blue" style={{ marginLeft: '8px', flexShrink: 0 }}>
                      {prompt.author || '未知'}
                    </Tag>
                  </div>

                  <Divider style={{ margin: '12px 0' }} />

                  <div
                    style={{
                      height: '90px',
                      overflow: 'auto',
                      fontSize: '14px',
                      color: '#4b5563',
                      marginBottom: '12px',
                    }}
                  >
                    {prompt.description}
                  </div>

                  <Divider style={{ margin: '12px 0' }} />

                  <div style={{ marginBottom: '12px' }}>
                    <Space size={[0, 8]} wrap>
                      <Tag
                        color={
                          prompt.category === '写作'
                            ? 'purple'
                            : prompt.category === '编程'
                            ? 'blue'
                            : prompt.category === '设计'
                            ? 'gold'
                            : 'green'
                        }
                      >
                        {prompt.category}
                      </Tag>
                      {prompt.tags?.map((tag, index) => (
                        <Tag key={tag} color={index % 2 === 0 ? 'cyan' : 'orange'}>
                          {tag}
                        </Tag>
                      ))}
                    </Space>
                  </div>

                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      flexWrap: 'wrap',
                    }}
                  >
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        color: '#9ca3af',
                        marginBottom: '8px',
                      }}
                    >
                      <ClockCircleOutlined style={{ marginRight: '4px' }} />
                      <span>{prompt.date || '未知日期'}</span>
                    </div>
                    <Space>
                      <Tooltip title="编辑">
                        <Button
                          size="small"
                          icon={<EditOutlined />}
                          style={{ background: '#3b82f6', color: '#fff' }}
                          onClick={(e) => {
                            e.stopPropagation();
                            showEditModal(prompt);
                          }}
                        />
                      </Tooltip>
                      <Tooltip title="优化">
                        <Button
                          size="small"
                          icon={<ThunderboltOutlined />}
                          style={{ background: '#f59e0b', color: '#fff' }}
                          onClick={(e) => {
                            e.stopPropagation();
                            showOptimizeModal(prompt);
                          }}
                        />
                      </Tooltip>
                      <Tooltip title="删除">
                        <Button
                          size="small"
                          icon={<DeleteOutlined />}
                          style={{ background: '#ef4444', color: '#fff' }}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleDeletePrompt(prompt.id);
                          }}
                        />
                      </Tooltip>
                      <Tooltip title="复制">
                        <Button
                          size="small"
                          icon={<CopyOutlined />}
                          style={{ background: '#8b5cf6', color: '#fff' }}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleCopyPrompt(prompt);
                          }}
                        />
                      </Tooltip>
                      {/* <Tooltip title="分享">
                        <Button
                          size="small"
                          icon={<ShareAltOutlined />}
                          style={{ background: '#10b981', color: '#fff' }}
                          onClick={(e) => {
                            e.stopPropagation();
                            showShareModal(prompt);
                          }}
                        />
                      </Tooltip> */}
                    </Space>
                  </div>
                </Card>
              ))
            ) : (
              <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '40px' }}>
                <p>没有找到匹配的提示词</p>
              </div>
            )}

            {currentPrompts.length > 0 && currentPrompts.length < DEFAULT_PAGE_SIZE && (
              <div
                style={{
                  borderRadius: '12px',
                  border: '2px dashed #d1d5db',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                  transition: 'all 0.3s',
                  ':hover': {
                    borderColor: '#8b5cf6',
                    boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)',
                  },
                }}
                onClick={showModal}
              >
                <div style={{ textAlign: 'center', padding: '16px' }}>
                  <div
                    style={{
                      width: '48px',
                      height: '48px',
                      backgroundColor: '#f3e8ff',
                      borderRadius: '50%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      margin: '0 auto 8px',
                    }}
                  >
                    <PlusOutlined style={{ color: '#8b5cf6', fontSize: '24px' }} />
                  </div>
                  <p style={{ color: '#8b5cf6', fontWeight: 500 }}>创建新提示词</p>
                </div>
              </div>
            )}
          </div>

          {filteredPrompts.length > DEFAULT_PAGE_SIZE && (
            <div style={{ display: 'flex', justifyContent: 'center', marginTop: '24px' }}>
              <Pagination
                current={currentPage}
                total={filteredPrompts.length}
                pageSize={DEFAULT_PAGE_SIZE}
                onChange={handlePageChange}
                showSizeChanger={false}
              />
            </div>
          )}
        </Content>
      </Layout>

      {/* 新建提示词模态框 */}
      <Modal
        title="新建提示词"
        visible={isModalVisible}
        onCancel={handleCancel}
        width={800}
        footer={[
          <Button key="back" onClick={handleCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={() => form.submit()}>
            确定
          </Button>,
        ]}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          {/* <Form.Item label="上传头像" name="avatar">
            <Upload
              listType="picture-card"
              showUploadList={false}
              beforeUpload={() => false}
            >
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传头像</div>
              </div>
            </Upload>
            <p style={{ color: '#9ca3af', fontSize: '12px', marginTop: '4px' }}>支持 JPG、PNG 格式</p>
          </Form.Item> */}
          <Collapse defaultActiveKey={['basic']} ghost>
            <Panel header="基础信息" key="basic">
              <Form.Item
                label="标题"
                name="title"
                rules={[{ required: true, message: '请输入标题' }]}
              >
                <Input placeholder="请输入提示词标题" />
              </Form.Item>

              <Form.Item label="描述" name="description">
                <TextArea rows={2} placeholder="请输入提示词描述" />
              </Form.Item>

              <Form.Item label="文件夹" name="folder" initialValue="全部提示词">
                <Select placeholder="请选择文件夹">
                  {folders.map((folder) => (
                    <Option key={folder.id} value={folder.name}>
                      {folder.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Panel>
            <Panel header="模板配置" key="template">
              <Form.Item label="模板类型" name="templateType">
                <Radio.Group
                  onChange={(e) => setTemplateType(e.target.value)}
                  optionType="button"
                  buttonStyle="solid"
                >
                  <Radio value="base">基础模板</Radio>
                  <Radio value="with_best_practice">包含最佳实践</Radio>
                </Radio.Group>
              </Form.Item>

              <Tabs activeKey={activeTab} onChange={setActiveTab}>
                <TabPane tab="基础模板" key="base">
                  <Form.Item name="base">
                    <TextArea rows={8} placeholder="基础模板内容" />
                  </Form.Item>
                </TabPane>

                {templateType === 'with_best_practice' && (
                  <>
                    <TabPane tab="复用模块前缀" key="reuse">
                      <Form.Item name="reusePrefix">
                        <TextArea rows={8} placeholder="可复用模块前缀内容" />
                      </Form.Item>
                    </TabPane>
                    <TabPane tab="Selenium" key="selenium">
                      <Form.Item name="selenium">
                        <TextArea rows={8} placeholder="Selenium最佳实践内容" />
                      </Form.Item>
                    </TabPane>
                    <TabPane tab="Playwright" key="playwright">
                      <Form.Item name="playwright">
                        <TextArea rows={8} placeholder="Playwright最佳实践内容" />
                      </Form.Item>
                    </TabPane>
                    <TabPane tab="两者结合" key="both">
                      <Form.Item name="both">
                        <TextArea rows={8} placeholder="两者结合的内容模板" />
                      </Form.Item>
                    </TabPane>
                  </>
                )}
              </Tabs>
            </Panel>
            <Panel header="提示词内容" key="content">
              <Form.Item
                label="角色"
                name="roleName"
                rules={[{ required: true, message: '请输入角色' }]}
              >
                <TextArea rows={2} placeholder="请输入提示词角色" />
              </Form.Item>

              <Form.Item
                label="Prompt内容"
                name="content"
                rules={[{ required: true, message: '请输入内容' }]}
              >
                <TextArea rows={4} placeholder="请输入提示词内容" />
              </Form.Item>
            </Panel>

            <Panel header="分类信息" key="meta">
              <Form.Item label="分类" name="category" initialValue="写作">
                <Select placeholder="请选择分类">
                  {categories.map((category) => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item label="标签" name="tags">
                <Select mode="tags" placeholder="请选择标签">
                  {tags.map((tag) => (
                    <Option key={tag} value={tag}>
                      {tag}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                label="版本"
                name="version"
                initialValue="latest"
                rules={[{ required: true, message: '请输入版本' }]}
              >
                <Input placeholder="请输入版本" />
              </Form.Item>
            </Panel>
          </Collapse>
        </Form>
      </Modal>

      {/* 新建文件夹模态框 */}
      <Modal
        title="新建文件夹"
        visible={isFolderModalVisible}
        onCancel={() => setIsFolderModalVisible(false)}
        footer={[
          <Button key="back" onClick={() => setIsFolderModalVisible(false)}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={() => folderForm.submit()}>
            确定
          </Button>,
        ]}
      >
        <Form form={folderForm} layout="vertical" onFinish={handleFolderSubmit}>
          <Form.Item
            label="文件夹名称"
            name="name"
            rules={[
              { required: true, message: '请输入文件夹名称' },
              {
                validator: (_, value) =>
                  folders.some((f) => f.name === value)
                    ? Promise.reject(new Error('文件夹已存在'))
                    : Promise.resolve(),
              },
            ]}
          >
            <Input placeholder="请输入文件夹名称" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 导入提示词模态框 */}
      <Modal
        title="导入提示词"
        visible={isImportModalVisible}
        onCancel={handleImportCancel}
        footer={[
          <Button key="back" onClick={handleImportCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={() => optimizeForm.submit()}>
            导入
          </Button>,
        ]}
      >
        <Tabs activeKey={importType} onChange={setImportType}>
          <TabPane tab="文本导入" key="text" icon={<FileTextOutlined />}>
            <Form form={optimizeForm} layout="vertical" onFinish={handleImport}>
              <Form.Item
                name="content"
                rules={[{ required: importType === 'text', message: '请输入提示词内容' }]}
              >
                <TextArea rows={6} placeholder="粘贴您的提示词内容..." />
              </Form.Item>
              <Form.Item label="保存至文件夹" name="folder" initialValue="全部提示词">
                <Select placeholder="请选择文件夹">
                  {folders.map((folder) => (
                    <Option key={folder.id} value={folder.name}>
                      {folder.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item label="分类" name="category" initialValue="写作">
                <Select placeholder="请选择分类">
                  {categories.map((category) => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                label="版本"
                name="version"
                initialValue="latest"
                rules={[{ required: true, message: '请输入版本' }]}
              >
                <Input placeholder="请输入版本" />
              </Form.Item>
            </Form>
          </TabPane>
          <TabPane tab="文件导入" key="file" icon={<CloudUploadOutlined />}>
            <Form form={optimizeForm} layout="vertical" onFinish={handleImport}>
              <Form.Item
                name="file"
                rules={[{ required: importType === 'file', message: '请上传文件' }]}
              >
                <Upload.Dragger
                  fileList={fileList}
                  onChange={handleFileUpload}
                  beforeUpload={() => false}
                  accept=".txt,.json,.md"
                  maxCount={1}
                >
                  <p className="ant-upload-drag-icon">
                    <CloudUploadOutlined style={{ fontSize: '32px', color: '#9ca3af' }} />
                  </p>
                  <p className="ant-upload-text">点击或拖拽文件到此处上传</p>
                  <p className="ant-upload-hint">支持 TXT, JSON, MD 文件</p>
                </Upload.Dragger>
              </Form.Item>
              <Form.Item label="保存至文件夹" name="folder" initialValue="全部提示词">
                <Select placeholder="请选择文件夹">
                  {folders.map((folder) => (
                    <Option key={folder.id} value={folder.name}>
                      {folder.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item label="分类" name="category" initialValue="写作">
                <Select placeholder="请选择分类">
                  {categories.map((category) => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                label="版本"
                name="version"
                initialValue="latest"
                rules={[{ required: true, message: '请输入版本' }]}
              >
                <Input placeholder="请输入版本" />
              </Form.Item>
            </Form>
          </TabPane>
          <TabPane tab="分享码导入" key="code" icon={<QrcodeOutlined />}>
            <Form form={optimizeForm} layout="vertical" onFinish={handleImport}>
              <Form.Item
                name="code"
                rules={[{ required: importType === 'code', message: '请输入分享码' }]}
              >
                <Input placeholder="请输入分享码" />
              </Form.Item>
              <Form.Item label="保存至文件夹" name="folder" initialValue="全部提示词">
                <Select placeholder="请选择文件夹">
                  {folders.map((folder) => (
                    <Option key={folder.id} value={folder.name}>
                      {folder.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item label="分类" name="category" initialValue="写作">
                <Select placeholder="请选择分类">
                  {categories.map((category) => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                label="版本"
                name="version"
                initialValue="latest"
                rules={[{ required: true, message: '请输入版本' }]}
              >
                <Input placeholder="请输入版本" />
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Modal>

      {/* 提示词详情模态框 */}
      <Modal
        title={`提示词详情 - ${selectedPrompt?.title || 'DeepSeek'}`}
        visible={isPromptDetailVisible}
        onCancel={handlePromptDetailCancel}
        width={700}
        footer={[
          <Button key="back" onClick={handlePromptDetailCancel}>
            关闭
          </Button>,
          <Button
            key="copy"
            icon={<CopyOutlined />}
            onClick={() => {
              handleCopyPromptContent(selectedPrompt);
            }}
          >
            复制到我的提示词
          </Button>,
        ]}
      >
        {selectedPrompt && (
          <div style={{ padding: '16px 16px' }}>
            <div
              style={{
                marginBottom: 24,
                lineHeight: '22px',
                fontSize: 14,
                color: '#000000D9',
              }}
            >
              <span
                style={{
                  fontWeight: 500,
                  marginRight: 8,
                  display: 'inline-flex',
                  alignItems: 'center',
                }}
              >
                <UserOutlined
                  style={{
                    marginRight: 4,
                    color: '#00000073',
                    fontSize: 14,
                  }}
                />
                作者：{selectedPrompt.author || '未设置'}
              </span>
              <span
                style={{
                  marginLeft: 16,
                  fontWeight: 500,
                  display: 'inline-flex',
                  alignItems: 'center',
                }}
              >
                <MailOutlined
                  style={{
                    marginRight: 4,
                    color: '#00000073',
                    fontSize: 14,
                  }}
                />
                邮箱：{selectedPrompt.email || '未设置'}
              </span>
            </div>

            <Divider
              style={{
                margin: '16px 0',
                borderColor: '#F0F0F0',
              }}
            />

            <h3
              style={{
                marginBottom: 16,
                fontSize: 16,
                fontWeight: 500,
                color: '#262626',
                lineHeight: 1.5,
              }}
            >
              提示词内容
            </h3>

            <div
              style={{
                background: '#FAFAFA',
                padding: 16,
                borderRadius: 2,
                border: '1px solid #F0F0F0',
                whiteSpace: 'pre-wrap',
                lineHeight: 1.8,
                fontFamily: '-apple-system, BlinkMacSystemFont, sans-serif',
                color: '#434343',
                fontSize: 14,
                maxHeight: 400,
                overflow: 'auto',
              }}
            >
              {selectedPrompt.content || '暂无提示词内容'}
            </div>
          </div>
        )}
      </Modal>

      {/* Prompt助手模态框 */}
      <Modal
        title="Prompt助手"
        visible={isAssistantVisible}
        onCancel={() => {
          setIsAssistantVisible(false);
          setGeneratedContent('');
        }}
        width={800}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setIsAssistantVisible(false);
              setGeneratedContent('');
            }}
          >
            取消
          </Button>,
          <Button
            key="generate"
            type="primary"
            onClick={() => assistantForm.submit()}
            loading={isGenerating}
          >
            生成提示词
          </Button>,
          <Button
            key="save"
            type="primary"
            onClick={async () => {
              if (!generatedContent) {
                message.warning('请先生成提示词');
                return;
              }
              const values = assistantForm.getFieldsValue();
              try {
                await promptPlusService.myPrompt.addMyPrompt({
                  title: `生成的提示词-${values.type}`,
                  description: `这是一个用于${values.type}的提示词`,
                  content: generatedContent,
                  category: values.type,
                  folder: 'all',
                  tags: [],
                  version: values.version || 'latest',
                  roleName: values.roleName,
                  base: values.base,
                  reusePrefix: values.reusePrefix,
                  selenium: values.selenium,
                  playwright: values.playwright,
                  both: values.both,
                });
                message.success('提示词保存成功');
                setIsAssistantVisible(false);
                setGeneratedContent('');
                fetchPrompts();
              } catch (error) {
                message.error('保存提示词失败');
                console.error(error);
              }
            }}
            disabled={!generatedContent}
          >
            保存提示词
          </Button>,
        ]}
      >
        <Form form={assistantForm} layout="vertical" onFinish={handleAssistantSubmit}>
          <Form.Item
            label="优化模型"
            name="model"
            rules={[{ required: true, message: '请选择优化模型' }]}
          >
            <Select placeholder="请选择优化模型">
              {models.map((model) => (
                <Option key={model.identifier} value={model.identifier}>
                  {model.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="提示词类型"
            name="type"
            rules={[{ required: true, message: '请选择提示词类型' }]}
          >
            <Select placeholder="请选择提示词类型">
              <Option value="写作">写作</Option>
              <Option value="编程">编程</Option>
              <Option value="设计">设计</Option>
              <Option value="营销">营销</Option>
              <Option value="学习">学习</Option>
              <Option value="工作">工作</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="具体要求"
            name="requirements"
            rules={[{ required: true, message: '请输入具体要求' }]}
          >
            <TextArea rows={6} placeholder="请详细描述您需要的提示词功能和要求..." />
          </Form.Item>

          <Form.Item label="高级选项">
            <Input.Group compact>
              <Form.Item name="tone" noStyle>
                <Select placeholder="语气风格" style={{ width: '33%' }}>
                  <Option value="formal">正式</Option>
                  <Option value="casual">随意</Option>
                  <Option value="professional">专业</Option>
                </Select>
              </Form.Item>
              <Form.Item name="length" noStyle>
                <Select placeholder="长度" style={{ width: '33%' }}>
                  <Option value="short">简短</Option>
                  <Option value="medium">中等</Option>
                  <Option value="long">详细</Option>
                </Select>
              </Form.Item>
              <Form.Item name="complexity" noStyle>
                <Select placeholder="复杂度" style={{ width: '34%' }}>
                  <Option value="simple">简单</Option>
                  <Option value="moderate">中等</Option>
                  <Option value="complex">复杂</Option>
                </Select>
              </Form.Item>
            </Input.Group>
          </Form.Item>

          <Form.Item label="生成的提示词">
            <TextArea
              rows={6}
              value={generatedContent}
              readOnly
              autoSize={{ minRows: 6, maxRows: 12 }}
              style={{ whiteSpace: 'pre-wrap' }}
            />
          </Form.Item>

          <Form.Item
            label="版本"
            name="version"
            initialValue="latest"
            rules={[{ required: true, message: '请输入版本' }]}
          >
            <Input placeholder="请输入版本" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑提示词模态框 */}
      <Modal
        title="编辑提示词"
        visible={isEditModalVisible}
        onCancel={handleEditCancel}
        width={800}
        footer={[
          <Button key="back" onClick={handleEditCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={() => editForm.submit()}>
            保存
          </Button>,
        ]}
      >
        <Form form={editForm} layout="vertical" onFinish={handleEditSubmit}>
          <Collapse defaultActiveKey={['basic']} ghost>
            <Panel header="基础信息" key="basic">
              <Form.Item
                label="标题"
                name="title"
                rules={[{ required: true, message: '请输入标题' }]}
              >
                <Input placeholder="请输入提示词标题" />
              </Form.Item>

              <Form.Item label="描述" name="description">
                <TextArea rows={2} placeholder="请输入提示词描述" />
              </Form.Item>

              <Form.Item label="文件夹" name="folder">
                <Select placeholder="请选择文件夹" optionLabelProp="label">
                  {folders.map((folder) => (
                    <Option key={folder.id} value={folder.id} label={folder.name}>
                      <Space>
                        {folder.icon || <FolderOutlined />}
                        {folder.name}
                      </Space>
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Panel>
            <Panel header="模板配置" key="template">
              <Form.Item label="模板类型" name="templateType">
                <Radio.Group
                  onChange={(e) => setTemplateType(e.target.value)}
                  optionType="button"
                  buttonStyle="solid"
                >
                  <Radio value="base">基础模板</Radio>
                  <Radio value="with_best_practice">包含最佳实践</Radio>
                </Radio.Group>
              </Form.Item>

              <Tabs activeKey={activeTab} onChange={setActiveTab}>
                <TabPane tab="基础模板" key="base">
                  <Form.Item name="base">
                    <TextArea rows={8} placeholder="基础模板内容" />
                  </Form.Item>
                </TabPane>

                {templateType === 'with_best_practice' && (
                  <>
                    <TabPane tab="复用模块前缀" key="reuse">
                      <Form.Item name="reusePrefix">
                        <TextArea rows={8} placeholder="可复用模块前缀内容" />
                      </Form.Item>
                    </TabPane>
                    <TabPane tab="Selenium" key="selenium">
                      <Form.Item name="selenium">
                        <TextArea rows={8} placeholder="Selenium最佳实践内容" />
                      </Form.Item>
                    </TabPane>
                    <TabPane tab="Playwright" key="playwright">
                      <Form.Item name="playwright">
                        <TextArea rows={8} placeholder="Playwright最佳实践内容" />
                      </Form.Item>
                    </TabPane>
                    <TabPane tab="两者结合" key="both">
                      <Form.Item name="both">
                        <TextArea rows={8} placeholder="两者结合的内容模板" />
                      </Form.Item>
                    </TabPane>
                  </>
                )}
              </Tabs>
            </Panel>
            <Panel header="提示词内容" key="content">
              <Form.Item
                label="角色"
                name="roleName"
                rules={[{ required: true, message: '请输入角色' }]}
              >
                <TextArea rows={2} placeholder="请输入提示词角色" />
              </Form.Item>

              <Form.Item
                label="Prompt内容"
                name="content"
                rules={[{ required: true, message: '请输入内容' }]}
              >
                <TextArea rows={4} placeholder="请输入提示词内容" />
              </Form.Item>
            </Panel>
            <Panel header="分类信息" key="meta">
              <Form.Item label="分类" name="category">
                <Select placeholder="请选择分类">
                  {categories.map((category) => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item label="标签" name="tags">
                <Select mode="tags" placeholder="请选择标签">
                  {tags.map((tag) => (
                    <Option key={tag} value={tag}>
                      {tag}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                label="版本"
                name="version"
                rules={[{ required: true, message: '请输入版本' }]}
              >
                <Input placeholder="请输入版本" />
              </Form.Item>
            </Panel>
          </Collapse>
        </Form>
      </Modal>

      {/* 分享提示词模态框 */}
      <Modal
        title="分享提示词"
        visible={isShareModalVisible}
        onCancel={handleShareCancel}
        footer={[
          <Button key="back" onClick={handleShareCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={() => shareForm.submit()}>
            分享
          </Button>,
        ]}
      >
        <Form form={shareForm} layout="vertical" onFinish={handleShareSubmit}>
          <Form.Item
            label="分享方式"
            name="method"
            rules={[{ required: true, message: '请选择分享方式' }]}
          >
            <Select placeholder="请选择分享方式">
              <Option value="email">电子邮件</Option>
              <Option value="link">生成分享链接</Option>
              <Option value="code">生成分享码</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="收件人邮箱"
            name="email"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input placeholder="请输入收件人邮箱" />
          </Form.Item>

          <Form.Item label="附加消息" name="message">
            <TextArea rows={3} placeholder="可输入附加消息（可选）" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 优化提示词模态框 */}
      <Modal
        title={`优化提示词 - ${optimizingPrompt?.title || ''}`}
        visible={isOptimizeModalVisible}
        onCancel={handleOptimizeCancel}
        width={800}
        footer={[
          <Button key="back" onClick={handleOptimizeCancel}>
            取消
          </Button>,
          <Button
            key="optimize"
            type="primary"
            onClick={handleOptimizeSubmit}
            loading={isOptimizing}
          >
            开始优化
          </Button>,
          <Button
            key="save"
            type="primary"
            onClick={handleSaveOptimizedPrompt}
            disabled={!optimizedContent}
          >
            保存优化结果
          </Button>,
        ]}
      >
        <Form form={optimizeForm} layout="vertical">
          <Form.Item label="优化模型" required>
            <Select
              placeholder="请选择优化模型"
              value={selectedModel}
              onChange={setSelectedModel}
              disabled={isOptimizing}
            >
              {models.map((model) => (
                <Option key={model.identifier} value={model.identifier}>
                  {model.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="优化模板" required>
            <Select
              placeholder="请选择优化模板"
              value={selectedTemplate}
              onChange={setSelectedTemplate}
              disabled={isOptimizing}
            >
              {promptTemplates
                .filter((t) => t.templateType === '优化提示词')
                .map((template) => (
                  <Option key={template.key} value={template.name}>
                    {template.name}
                  </Option>
                ))}
            </Select>
          </Form.Item>

          <Form.Item label="原始提示词">
            <TextArea rows={4} value={optimizingPrompt?.content || ''} readOnly />
          </Form.Item>

          <Form.Item label="优化后的提示词">
            <TextArea
              ref={optimizedTextAreaRef}
              rows={6}
              value={optimizedContent}
              readOnly
              autoSize={{ minRows: 6, maxRows: 12 }}
              style={{ whiteSpace: 'pre-wrap' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default PromptManagement;
